<template>
  <!-- 搜索工作栏 -->
  <ContentWrap class="mb-4">
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="定位时间" prop="locationTime">
        <el-date-picker
          v-model="queryParams.locationTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 视图切换按钮 -->
  <ContentWrap class="mb-4">
    <div class="view-mode-switch">
      <el-button
        @click="toggleViewMode('table')"
        :type="viewMode === 'table' ? 'primary' : 'default'"
        icon="el-icon-table"
      >
        行踪轨迹
      </el-button>
      <el-button
        @click="toggleViewMode('map')"
        :type="viewMode === 'map' ? 'primary' : 'default'"
        icon="el-icon-map-location"
      >
        轨迹分析
      </el-button>
      <el-button
        @click="toggleViewMode('frequent')"
        :type="viewMode === 'frequent' ? 'primary' : 'default'"
        icon="el-icon-place"
      >
        常去地分析
      </el-button>

      <!-- 分页 -->
      <Pagination
        v-if="viewMode === 'table'"
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        :pager-count="5"
        :showJumper="false"
      />
    </div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap v-if="viewMode === 'table'">
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column
        label="定位时间"
        align="center"
        prop="locationTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        width="150"
        label="经度"
        align="center"
        prop="lng"
        :formatter="numberFormatter"
      />
      <el-table-column
        width="150"
        label="纬度"
        align="center"
        prop="lat"
        :formatter="numberFormatter"
      />
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column
        width="120"
        label="数据来源"
        align="center"
        prop="dataType"
        :formatter="dataTypeFormatter"
      />
    </el-table>
  </ContentWrap>

  <!-- 地图模式 -->
  <ContentWrap v-if="viewMode === 'map'" class="map-content-wrap">
    <div class="map-container">
      <!-- 地图容器 -->
      <div id="locationMap" ref="mapRef" class="map" @click.prevent></div>

      <!-- 地图信息弹窗 -->
      <el-dialog
        v-model="showMarkerDetail"
        v-if="showMarkerDetail || selectedLocation"
        title="定位详情"
        width="400px"
        :close-on-click-modal="false"
        append-to-body
        :before-close="handleDialogClose"
        :modal="true"
        :destroy-on-close="false"
        class="marker-dialog"
      >
        <div v-if="selectedLocation" class="marker-detail">
          <div class="detail-item">
            <span class="detail-label">定位时间：</span>
            <span class="detail-value">{{
                selectedLocation.locationTime ? dateTimeFormatter(selectedLocation.locationTime) : '-'
              }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">经度：</span>
            <span class="detail-value">{{
                selectedLocation.lng ? numberFormatter(null, null, selectedLocation.lng) : '-'
              }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">纬度：</span>
            <span class="detail-value">{{
                selectedLocation.lat ? numberFormatter(null, null, selectedLocation.lat) : '-'
              }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">详细地址：</span>
            <span class="detail-value">{{ selectedLocation.address || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">数据来源：</span>
            <span class="detail-value">{{
                selectedLocation.dataType ? dataTypeFormatter(null, null, selectedLocation.dataType) : '-'
              }}</span>
          </div>
        </div>
      </el-dialog>
    </div>
  </ContentWrap>

  <!-- 常去地分析视图（硬编码10条数据） -->
  <ContentWrap v-if="viewMode === 'frequent'">
    <el-card>

      <el-table
        :data="frequentLocations"
        :stripe="true"
        :show-overflow-tooltip="true"
        border
      >
        <el-table-column label="排名" type="index" width="60" align="center" />
        <el-table-column label="详细地址" align="center" prop="address" min-width="200" />
        <el-table-column
          label="出现次数"
          align="center"
          prop="count"
          width="120"
          sortable
        />
        <el-table-column
          label="首次出现时间"
          align="center"
          prop="firstTime"
          width="180"
          :formatter="dateFormatter"
        />
        <el-table-column
          label="末次出现时间"
          align="center"
          prop="lastTime"
          width="180"
          :formatter="dateFormatter"
        />
      </el-table>
    </el-card>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <LocationForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, watch, nextTick, onUnmounted } from 'vue'
import Pagination from '@/components/Pagination/index.vue'
import { dateFormatter, dateTimeFormatter } from '@/utils/formatTime'
import 'leaflet/dist/leaflet.css'
import * as L from 'leaflet';
import {FrequentLocation, LocationApi, LocationVO} from '@/api/member/location'
import LocationForm from './LocationForm.vue'
import {ElMessage} from "element-plus";

/** 定位信息 列表组件 */
defineOptions({ name: 'LocationList' })

// 视图模式：table-表格模式，map-地图模式
const viewMode = ref<'table' | 'map' | 'frequent'>('table')
// 地图实例
let mapInstance: L.Map | null = null
// 标记点图层组
let markerLayer: L.FeatureGroup<any> | null = null
// 轨迹线图层
let polylineLayer: L.FeatureGroup<any> | null = null
// 箭头图层组
let arrowLayer: L.FeatureGroup<any> | null = null
// 地图容器引用
const mapRef = ref<HTMLDivElement | null>(null)
// 是否显示标记详情
const showMarkerDetail = ref(false)
// 当前选中的定位信息
const selectedLocation = ref<LocationVO | null>(null)

// 常去地相关状态
const frequentLocations = ref<FrequentLocation[]>([]) // 接口返回的10条数据
const frequentLoading = ref(false) // 加载状态

// 列表状态
const loading = ref(true)
const list = ref<LocationVO[]>([])
const total = ref(0)
const formRef = ref()
const queryFormRef = ref()

// 接收父组件的personId
const { personId } = defineProps({
  personId: {
    type: [String, Number],
    required: true
  }
})

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  locationTime: [],
  personId: personId,
  lng: undefined,
  lat: undefined,
  address: undefined,
  dataType: undefined,
  cameraNo: undefined,
  faceUrl: undefined
})

/** 切换视图模式 */
const toggleViewMode = (mode: 'table' | 'map' | 'frequent') => {
  viewMode.value = mode
  if (mode === 'map') {
    nextTick(() => {
      initMap()
    })
  }else if (mode === 'frequent') {
    // 切换到常去地模式时加载数据
    nextTick(() => getFrequentLocations())
  }
}

/** 调用接口获取常去地数据（10条） */
const getFrequentLocations = async () => {
  if (!personId) return

  frequentLoading.value = true
  try {
    // 调用接口（使用指定的getFrequentLocations方法）
    const response = await LocationApi.getFrequentLocations(Number(personId))
    // 假设接口直接返回FrequentLocation[]数组
    frequentLocations.value = response || []
    // 确保只显示10条（如果后台返回更多）
    if (frequentLocations.value.length > 10) {
      frequentLocations.value = frequentLocations.value.slice(0, 10)
    }
  } catch (error) {
    console.error('获取常去地数据失败:', error)
    ElMessage.error('加载常去地数据失败')
    frequentLocations.value = []
  } finally {
    frequentLoading.value = false
  }
}

/** 初始化地图 */
const initMap = () => {
  if (!mapRef.value) return

  // 清除现有地图实例
  if (mapInstance) {
    mapInstance.remove()
  }

  // 创建地图实例
  mapInstance = L.map(mapRef.value, {
    minZoom: 6,
    maxZoom: 18,
    attributionControl: false
  })

  // 设置地图瓦片源
  // 加载地图瓦片
  L.tileLayer(import.meta.env.VITE_MAP_TILE_URL, {
    errorTileUrl: '',
    attribution: '地图数据 © 高德地图',
    tileSize: 256,
    zoomOffset: 0
  }).addTo(mapInstance);
  // L.tileLayer('http://localhost:8000/map/{z}/{x}/{y}/tile.png', {
  //   errorTileUrl: '',
  //   tileSize: 256,
  //   zoomOffset: 0
  // }).addTo(mapInstance)

  // 创建标记点图层组、轨迹线图层和箭头图层
  markerLayer = L.featureGroup().addTo(mapInstance)
  polylineLayer = L.featureGroup().addTo(mapInstance)
  arrowLayer = L.featureGroup().addTo(mapInstance)

  // 添加地图容器点击事件处理
  mapRef.value.addEventListener('click', (e) => {
    e.stopPropagation()
    e.preventDefault()
  }, { passive: false })

  // 添加定位标记和轨迹
  addLocationMarkersAndTrack()

  // 调整地图视野
  adjustMapView()
}

/** 添加定位标记和轨迹线 */
const addLocationMarkersAndTrack = () => {
  if (!markerLayer || !polylineLayer || !arrowLayer || !mapInstance) return

  // 清除现有标记、轨迹和箭头
  markerLayer.clearLayers()
  polylineLayer.clearLayers()
  arrowLayer.clearLayers()

  // 按定位时间排序（确保时间从早到晚）
  const sortedList = [...list.value].sort((a, b) => {
    return new Date(a.locationTime).getTime() - new Date(b.locationTime).getTime()
  })

  // 收集有效坐标点用于绘制轨迹
  const coordinates: L.LatLngExpression[] = []

  // 添加标记点
  sortedList.forEach((location, index) => {
    if (location.lng && location.lat) {
      // 转换为数字类型
      const lat = Number(location.lat)
      const lng = Number(location.lng)

      // 添加到坐标数组
      coordinates.push([lat, lng])

      // 创建不同的图标，第一个点（时间最早）和最后一个点（时间最晚）使用不同样式
      let iconHtml = ''
      if (index === 0) {
        // 起点 - 绿色（时间最早）
        iconHtml = `<div style="width: 36px; height: 36px; background-color: #4CAF50; border: 2px solid white; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);">
                     <i class="el-icon-circle-check" style="font-size: 18px;"></i>
                   </div>`
      } else if (index === sortedList.length - 1) {
        // 终点 - 红色（时间最晚）
        iconHtml = `<div style="width: 36px; height: 36px; background-color: #F44336; border: 2px solid white; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);">
                     <i class="el-icon-flag" style="font-size: 18px;"></i>
                   </div>`
      } else {
        // 中间点 - 蓝色
        iconHtml = `<div style="width: 30px; height: 30px; background-color: #2196F3; border: 2px solid white; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);">
                     <i class="el-icon-location" style="font-size: 16px;"></i>
                   </div>`
      }

      const customIcon = L.divIcon({
        className: 'location-marker',
        html: iconHtml,
        iconSize: index === 0 || index === sortedList.length - 1 ? [36, 36] : [30, 30],
        iconAnchor: index === 0 || index === sortedList.length - 1 ? [18, 18] : [15, 15],
      })

      // 创建标记并添加到图层
      const marker = L.marker([lat, lng], {
        icon: customIcon,
        zIndexOffset: 1000 - index // 确保后面的点在上面
      }).addTo(markerLayer as any)

      // 添加时间标签
      const timeStr = dateTimeFormatter(location.locationTime)
      marker.bindTooltip(`${timeStr}`, {
        permanent: true,
        direction: 'top',
        className: 'location-label'
      })

      // 标记点点击事件处理
      marker.on('click', async (event: L.LeafletMouseEvent) => {
        event.originalEvent.stopPropagation();
        event.originalEvent.preventDefault();

        // 设置选中定位信息
        selectedLocation.value = null;
        await nextTick();
        selectedLocation.value = { ...location };
        await nextTick();
        showMarkerDetail.value = true;
      })
    }
  })

  // 绘制轨迹线（如果有多个有效点）
  if (coordinates.length > 1) {
    const trackLine = L.polyline(coordinates, {
      color: 'red',
      weight: 4,
      opacity: 0.7,
      lineJoin: 'round'
    }).addTo(polylineLayer as any)

    // 添加箭头指示方向（从时间早的点指向时间晚的点）
    addDirectionArrowsToPolyline(trackLine)
  }
}

/** 为轨迹线添加方向箭头，指示从时间早到时间晚的移动方向 */
const addDirectionArrowsToPolyline = (polyline: L.Polyline) => {
  if (!mapInstance || !arrowLayer) return

  // 获取并处理点数据，确保是一维数组
  const latLngs = polyline.getLatLngs();
  const points: L.LatLng[] = Array.isArray(latLngs[0]) ?
    (latLngs as L.LatLng[][]).flat() :
    (Array.isArray(latLngs) ? latLngs : [latLngs]) as L.LatLng[];

  // 为每段线段添加箭头
  for (let i = 0; i < points.length - 1; i++) {
    const p1 = points[i];  // 时间较早的点
    const p2 = points[i + 1];  // 时间较晚的点

    // 确保p1和p2是LatLng对象
    if (!(p1 instanceof L.LatLng) || !(p2 instanceof L.LatLng)) {
      continue;
    }

    // 计算线段中点作为箭头位置（从时间早的点指向时间晚的点）
    const midLat = (p1.lat + p2.lat) / 2;
    const midLng = (p1.lng + p2.lng) / 2;

    // 计算方向角度（从p1指向p2的方向）
    const angle = Math.atan2(p2.lng - p1.lng, p2.lat - p1.lat) * 180 / Math.PI;

    // 创建箭头图标
    const arrowIcon = L.divIcon({
      className: 'direction-arrow',
      html: `<div style="width: 20px; height: 20px; transform: rotate(${angle}deg); color: red;">
               <i class="el-icon-arrow-right" style="font-size: 20px; text-shadow: 0 1px 2px rgba(0,0,0,0.3);"></i>
             </div>`,
      iconSize: [20, 20],
      iconAnchor: [10, 10]
    });

    // 添加箭头标记到箭头图层
    L.marker([midLat, midLng], {
      icon: arrowIcon,
      zIndexOffset: 600  // 确保箭头显示在轨迹线上方
    }).addTo(arrowLayer as any);
  }
}

/** 调整地图视野 */
const adjustMapView = () => {
  if (!mapInstance || !markerLayer) return

  const validPoints = list.value
    .filter(loc => loc.lng && loc.lat)
    .map(loc => L.latLng(Number(loc.lat), Number(loc.lng)))

  if (validPoints.length > 0) {
    const bounds = L.latLngBounds(validPoints)
    mapInstance.fitBounds(bounds, {
      padding: [50, 50],
      maxZoom: 15
    })
  } else {
    // 默认位置（可根据实际情况调整）
    mapInstance.setView([30.2741, 120.1551], 13)
  }
}

/** 弹窗关闭时重置状态 */
const handleDialogClose = () => {
  showMarkerDetail.value = false
  selectedLocation.value = null
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await LocationApi.getLocationPage(queryParams)
    list.value = data.list
    total.value = data.total

    if (viewMode.value === 'map') {
      await nextTick(() => {
        addLocationMarkersAndTrack()
        adjustMapView()
      })
    }
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 经纬度格式化函数 - 保留6位小数
const numberFormatter = (_row: any, _column: any, value: number) => {
  // 处理空值或无效值
  if (value === null || value === undefined || isNaN(value)) {
    return '-';
  }
  // 保留6位小数
  return value.toFixed(6);
};

// 数据来源格式化
const dataTypeFormatter = (_row: any, _column: any, value: number) => {
  const dataTypeMap = {
    1: '人脸抓拍',
    2: '航班'
  };
  return dataTypeMap[value] || '未知';
};

// 监听视图模式变化
watch(viewMode, (newMode) => {
  if (newMode === 'map') {
    const scrollPos = window.scrollY;
    nextTick(() => {
      initMap();
      window.scrollTo({ top: scrollPos, behavior: 'auto' });
    })
  }
})

// 监听列表数据变化
watch(list, () => {
  if (viewMode.value === 'map') {
    addLocationMarkersAndTrack()
    adjustMapView()
  }
})

// 监听弹窗显示状态
watch(showMarkerDetail, (newVal) => {
  if (newVal && mapInstance) {
    // 保持地图容器高度
    const mapContainer = document.querySelector('.map-container') as HTMLElement | null;
    if (mapContainer) {
      mapContainer.style.height = '600px';
      mapContainer.style.overflow = 'hidden';
    }

    // 防止页面滚动
    document.body.style.overflow = 'hidden';
    mapInstance.invalidateSize();
  } else {
    // 恢复页面滚动
    document.body.style.overflow = '';
  }
})

/** 初始化 */
onMounted(() => {
  getList()

  window.addEventListener('resize', () => {
    if (mapInstance) {
      mapInstance.invalidateSize()
    }
  })
})

/** 组件卸载时清理 */
onUnmounted(() => {
  if (mapInstance) {
    mapInstance.remove()
    mapInstance = null
  }
  window.removeEventListener('resize', () => {
    if (mapInstance) {
      mapInstance.invalidateSize()
    }
  })
})
</script>

<style scoped>
/* 视图切换按钮样式 */
.view-mode-switch {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 地图容器样式 */
.map-content-wrap {
  position: relative;
  min-height: 600px;
  flex-shrink: 0;
}

.map-container {
  position: relative;
  height: 600px !important;
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-height: 600px;
  max-height: 600px;
}

.map {
  width: 100%;
  height: 100%;
}

/* 弹窗样式 */
:deep(.marker-dialog) {
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
  z-index: 10000 !important;
}

:deep(.el-dialog__wrapper) {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 !important;
  overflow: hidden !important;
  position: fixed !important;
}

/* 标记详情样式 */
.marker-detail {
  padding: 10px 0;
}

.detail-item {
  margin-bottom: 12px;
}

.detail-label {
  display: inline-block;
  width: 100px;
  color: #606266;
  font-weight: 500;
}

.detail-value {
  color: #303133;
  word-break: break-all;
}

/* 地图标记和轨迹样式 */
:deep(.location-marker),
:deep(.direction-arrow) {
  display: block !important;
  visibility: visible !important;
  z-index: 1000 !important;
}

:deep(.leaflet-marker-icon) {
  display: block !important;
  opacity: 1 !important;
}

:deep(.location-label) {
  background-color: rgba(255, 255, 255, 0.9);
  border: 1px solid #ccc;
  border-radius: 3px;
  padding: 4px 6px;
  font-size: 12px;
  white-space: nowrap;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

:deep(.leaflet-container) {
  height: 100% !important;
  width: 100% !important;
  overflow: hidden !important;
  position: relative !important;
  z-index: 1;
}

/* 分页样式调整 */
:deep(.el-pagination) {
  margin-left: auto;
}
</style>
